// pages/post/post.js
import Toast from '../../miniprogram_npm/@vant/weapp/lib/toast/toast';
const db = wx.cloud.database()
const dbF = wx.cloud.database().collection('Follow')
const dbT = wx.cloud.database().collection('Top')
const dbU = wx.cloud.database().collection('User')
const dbM = wx.cloud.database().collection('Main')
const _ = db.command

Page({

  /**
   * 页面的初始数据
   */
  data: {
    Main: {},
    Follow:[],
    id:'',
    submit_disable:false,

    scoreShow: false, //评分弹出层
    score: 0, //打分的分值

    isLike: false,
    pump_isShow: false,
    recieve_isShow: false,
    pump_describe: '',
    answer_describe: '',

    answer_question_describe: '',
    answer_question_data: '',
    img:[],
    fileList:[],

    selected_question_ans: [],
    selected_question_date:'',
    selected_question_picker:'',
    selected_question_img:[],
    selected_question_state:'',
    selected_question_title:'',
    selected_question_describe:'',
    selected_question_zan:0,
    questioner_pic:'',
    selected_question_openid:'',
    selected_question_contact:'',

    openid:'',
    pick_isshow:false,
    ques_isshow:false,
    answ_isshow:false,
    admin_isshow:false,
    vol_assign_isshow:false,

    //指定义工的弹出层界面
    selected_vol_name: '',
    selected_vol_basedInfo: '',
    selected_vol_pic_url: '',
    selected_vol_openid: '',
    selected_vol_solved: 0,
    selected_vol_zan: 0,
    selected_vol_introduction: '这位义工还没有填写自我介绍哦~',

  },

//添加图片
afterRead(event) {
  let that = this;
  // console.log(event)
  let obj = event.detail

  console.log(obj)
  let NewfileList = {}
  NewfileList.url = obj.file.url
  NewfileList.name = "image" + obj.index
  NewfileList.index = obj.index
  NewfileList.type = 'image'
  NewfileList.size = obj.file.size
  let fileList = []
  fileList.push(...that.data.fileList, NewfileList);
  that.setData({
    fileList
  })
  console.log(that.data.fileList)
},

inttodate(numint){
  var num = numint.toString()
  console.log(num)
  var year = num.substring(0,4)
  var month = num.substring(4,6)
  var date = num.substring(6,8)
  var hour = num.substring(8,10)
  var min = num.substring(10,12)
  
  var ddate = year+"年"+month+"月"+date+"日"+hour+":"+min
  return ddate
},

uploadFilePromise(fileName, chooseResult) {
  return wx.cloud.uploadFile({
    cloudPath: fileName,
    filePath: chooseResult.url
  }).then(res => {
    console.log(res.fileID)
    let img=[]
    img.push(...this.data.img,res.fileID)
    this.setData({
      img
    })
  }).catch(error => {});
},


  // 点赞 图片变色，数量+1
  number_of_likes_onChange() {
    let bol = this.data.isLike;
    if(bol==true){
      db.collection('Main').where({
        _id:this.data.id
      }).update({
        data:{
          zan:_.inc(-1)
        }
      })
    }else{
      db.collection('Main').where({
        _id:this.data.id
      }).update({
        data:{
          zan:_.inc(1)
        }
      })
    }
    this.setData({
      isLike: !bol
    })

//test
// db.collection('Main').where({
//   _id:this.data.id
// }).update({
//   data:{
//     state:'unsolved',
//     picker:''
//   }
// })
//test
  },

  //删除选中的图片
  delete(event) {
    let n = event.detail.index
    let fileList = this.data.fileList
    fileList.splice(n, 1)
    this.setData({
      fileList
    })
  },

  imageonClick(e) {
    let current = e.target.dataset.src;
    wx.previewImage({
      current: current,
      urls: this.data.selected_question_img
    })
  },

  followimageonClick(e) {
    let current = e.target.dataset.src;
    wx.previewImage({
      urls:[current]
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    wx.showLoading({
      title: '加载中',
      mask: true
    })
    this.setData({
      id:options.id
    })
    this.getOpenid()
  },

  //义工回答完成给同学发消息，以及同学追问给义工发消息
  send_message:function(id){
    db.collection('Mes_2').add({
      data:{
        post_title:this.data.Main.title,
        postid:this.data.Main._id,
        date:new Date(),
        id:id,//义工openid
        read:false
      }
    })
  },
  //同学追问给义工发弹窗提示
  send_message_to_vol: function (picker) {
    db.collection('Message').add({
      data: {
        id: picker,
        postid: this.data.Main._id
      },
      success: function (res) {
        console.log(res)
      }
    })
  },
  //义工点击接单按钮
  pick:function(){
    db.collection('Main').where({
      _id:this.data.id
    }).get().then(res => {
      if(res.data[0].state != 'unsolved' || res.data[0].picker != ''){
        console.log(res)
        wx.showToast({
          title: '该问题已被抢哦～',
        })
        this.refresh()
      }else{
        db.collection('Main').where({
          _id:this.data.id
        }).update({
          data:{
            state:'solving',
            picker:this.data.openid
          }
        }).then(res =>{
          this.refresh()
        }).then(res=>{
          Toast.success('接单成功!୧(๑•̀⌄•́๑)૭');
        })
      }
      
    })
  },

  refresh:function(){
    this.setData({
      pick_isshow:false,
      ques_isshow:false,
      answ_isshow:false,
      admin_isshow:false
    })
    db.collection('Main').where({
      _id:this.data.id
    }).get().then(res => {
      this.setData({
        Main:res.data[0]
      })
      if(this.data.Main.ans.length==1){
        console.log(this.data.Main.ans[0])
        dbU.where({
          _openid:this.data.Main.ans[0]
        }).get().then(res => {
          this.setData({
            selected_vol_name: res.data[0].name,
            selected_vol_basedInfo: res.data[0].class,
            selected_vol_pic_url: res.data[0].url,
            selected_vol_openid: res.data[0]._openid,
            selected_vol_introduction: res.data[0].introduction
          })
          dbM.where({
            picker: res.data[0]._openid,
            state: _.in(['solved','solving'])
          }).get().then(res => {
            let zzan = 0
            console.log(res.data)
            for (let i = 0; i < res.data.length; i++) {
              zzan = zzan + res.data[i].zan
            }
            this.setData({
              selected_vol_zan: zzan,
              selected_vol_solved: res.data.length
            })
          })
        })
      }
      this.setData({
        selected_question_ans:this.data.Main.ans,
        selected_question_date:this.inttodate(this.data.Main.date),
        selected_question_img:this.data.Main.img,
        selected_question_state:this.data.Main.state,
        selected_question_title:this.data.Main.title,
        selected_question_describe:this.data.Main.des,
        selected_question_zan:this.data.Main.zan,
        selected_question_openid:this.data.Main._openid,
        selected_question_picker:this.data.Main.picker,
        selected_question_contact:this.data.Main.contact
    })
    }).then(res =>{
      db.collection('User').where({
        _openid:this.data.selected_question_openid
      }).get().then(res =>{
        this.setData({
          questioner:res.data[0]
        })
      })

      dbF.where({
        mainid:this.data.id
      }).get().then(res=>{
        this.setData({
          Follow:res.data
        })
      }).then(res=>{
        for(let i = 0;i<this.data.Follow.length;i++){
          db.collection('User').where({
            _openid:this.data.Follow[i]._openid
          }).get().then(res=>{
            this.setData({
              ["Follow["+i+"].info"]:res.data[0],
              ["Follow["+i+"].date"]:this.inttodate(this.data.Follow[i].date)
            })
          })
        }
      })
      
    }).then(res =>{
      console.log(this.data.selected_question_picker)
      console.log('AAA')
  
      if(this.data.selected_question_picker == this.data.openid
        && this.data.selected_question_state == 'solving'){
        this.setData({
          answ_isshow:true
        })
      }
  
      if(this.data.selected_question_picker == '' && this.data.selected_question_state == 'unsolved' && this.data.openid !=this.data.selected_question_openid){
        for(let i=0;i<this.data.selected_question_ans.length;i++)
        if(this.data.selected_question_ans[i] == this.data.openid){
        this.setData({
          pick_isshow:true
        })
      }
      }
  
      if(this.data.openid == this.data.selected_question_openid
        && this.data.selected_question_state != 'solved'){
        this.setData({
          ques_isshow:true
        })
      }

      if(this.data.info.identity == 'A'){
        this.setData({
        admin_isshow:true
      })}
      
      wx.hideLoading({
      })
    })
  },

  //上榜
  post_up:function(){
    dbT.where({
      sub:this.data.Main.sub
    }).update({
      data:{
        top:_.addToSet(this.data.Main._id)
      },
      success:function(res){
        wx.showToast({
          title: '置顶成功!',
        })
      }
    })
  },

  //删除
  post_delete:function(){
    wx.showModal({
      title: '确认操作',
      content: '确定要删除此问题吗？（操作不可逆',
      success: res=>{
        if (res.confirm) {
          wx.showToast({
            title: '请稍等',
            icon:'loading'
          })
          db.collection('Main').where({
            _id:this.data.id
          }).remove({
            success:function(res){
              wx.showToast({
                title: '删除成功',
                icon: 'success',
                duration: 2000//持续的时间
              })
      
      
              var start=Date.now();
                while(true){
                  var nowTime=Date.now();
                  var offset=nowTime-start;
                  if(offset>=1000)
                    break;
                }
             
              wx.navigateBack()
      
            },
          })
        } else if (res.cancel) {
          console.log('取消')
        }
      }
    })
 
 
  },


  // 获取用户openid
  getOpenid() {
    let that = this;
    wx.cloud.callFunction({
      name: 'getOpenid',
      complete: res => {
        console.log('云函数获取到的openid: ', res.result.openId)
        var openid = res.result.openId;
        that.setData({
          openid: openid
        })

        db.collection('User').where({
          _openid:res.result.openId
        }).get().then(res=>{
          this.setData({
            info:res.data[0]
          })
        }).then(res=>{
          this.refresh()
        })
        
      }
    })
    
  },

  //指定义工界面
  showVolAssign:function(){
    this.setData({
      vol_assign_isshow: true
    })
  },

  vol_assign_onClose:function(){
    this.setData({
      vol_assign_isshow: false
    })
  },
  //指定的义工回答过的问题跳转
  solved_question_list() {
    var vol_id = this.data.selected_vol_openid;
    var vol_name = this.data.selected_vol_name;
    this.setData({
      vol_intro_isShow: false,
    });
    wx: wx.navigateTo({
      url: '../vol_lst/vol_list?id=' + vol_id + '&name=' + vol_name,
    })
  },


  //回答问题界面
  recieve() {
    this.setData({
      recieve_isShow: true
    })
  },

  dtConvert(myDate){
    let year=myDate.getFullYear();
    let month=myDate.getMonth();
    let date=myDate.getDate();
    let hour=myDate.getHours();
    let minute=myDate.getMinutes();
    //Date1,年月日
    let Date1=year*10000+(month+1)*100+date;
    //Time,时和分
    let Time=hour*100+minute;
    //DateTime年月日时分
    let DateTime=year*100000000+(month+1)*1000000+date*10000+hour*100+minute;
    return {Date:Date1,Time:Time,DateTime:DateTime};
},

  send_answer() {
    this.setData({
      submit_disable:true
    })

    wx.showLoading({
      title: '加载中',
    })
    
    //暂停两秒
    var start=Date.now();
    while(true){
    var nowTime=Date.now();
    var offset=nowTime-start;
    if(offset>=2000)
    break;
    }

    if (this.data.answer_describe != '') {
      //提交问题
      // 获取页面数据????
    let date = new Date();  //当前标准时间格式
    var datenum = this.dtConvert(date).DateTime
    console.log(datenum)

    // 上传图片
    wx.cloud.init();
    const {
      fileList
    } = this.data;
    if (!fileList.length) {//无图片
      let that = this
      let that_id = this.data.Main._openid

      dbF.add({
        data:{
          date:datenum,
          des:this.data.answer_describe,
          img:this.data.img,
          mainid:this.data.id
        },
        success:function(res){
          wx.showToast({
            title: '提交成功!୧(๑•̀⌄•́๑)૭',
            icon: 'success',
            duration: 2000//持续的时间
          })

          that.send_message(that_id)

          that.refresh()
        }
      })
      
      if(this.data.Main.phoneNumber!=undefined){
        var phone_ = this.data.Main.phoneNumber
        var regex = /^(13[0-9]{9})|(15[0-9]{9})|(17[0-9]{9})|(18[0-9]{9})|(19[0-9]{9})$/;
        if (phone_.match(regex)) {//手机号格式校验
          // console.log("手机号是"+phone_)
          console.log("短信发给："+phone_)
          wx.request({
            method:'POST',
            url: getApp().data.root + '/studyaider/sendtostudent',
            header:{
              "Content-Type": "application/x-www-form-urlencoded"
            },
            data:{
              phone  : phone_
            },
            success:function(res){
              console.log(res)
            }
          })
        }//手机号格式校验正确则发短信提醒

      }

      this.setData({
        recieve_isShow:false,
        answer_describe:'',
        img:[],
        fileList: [],
      })

      this.setData({
        submit_disable:false
      })
    } else {//有图片
      const uploadTasks = fileList.map((file, index) => this.uploadFilePromise(`photo/${this.data.openid}-photo${index}${datenum}.png`, file));
      wx.showToast({
        title: '上传中',
        icon: 'loading'
      })
      Promise.all(uploadTasks)
        .then(res => {
          wx.showToast({
            title: '上传成功',
            icon: 'none'
          })

          var start=Date.now();
          while(true){
          var nowTime=Date.now();
          var offset=nowTime-start;
          if(offset>=2000)
          break;}
          
          this.setData({
            cloudPath: res,
            fileList: []
          })
          let that = this
          let that_id = this.data.Main._openid
          dbF.add({
            data:{
              date:datenum,
              des:this.data.answer_describe,
              img:this.data.img,
              mainid:this.data.id
            },
            success:function(res){
              wx.showToast({
                title: '提交成功!',
                icon: 'success',
                duration: 2000//持续的时间
              })

              that.send_message(that_id)

              that.refresh()
            }
            
          })

          if(this.data.Main.phoneNumber!=undefined){
            var phone_ = this.data.Main.phoneNumber
            var regex = /^(13[0-9]{9})|(15[0-9]{9})|(17[0-9]{9})|(18[0-9]{9})|(19[0-9]{9})$/;
            if (phone_.match(regex)) {//手机号格式校验
              // console.log("手机号是"+phone_)
              console.log("短信发给："+phone_)
              wx.request({
                method:'POST',
                url: getApp().data.root + '/studyaider/sendtostudent',
                header:{
                  "Content-Type": "application/x-www-form-urlencoded"
                },
                data:{
                  phone  : phone_
                },
                success:function(res){
                  console.log(res)
                }
              })
            }//手机号格式校验正确则发短信提醒
            
          }
          this.setData({
            recieve_isShow:false,
            answer_describe:'',
            img:[],
            fileList: [],
          })

          this.setData({
            submit_disable:false
          })
        })
        .catch(e => {
          wx.showToast({
            title: '上传失败',
            icon: 'none'
          });
          console.log(e);
        });
    }
    //上传图片结束
    } else {
      Toast.fail('还有信息未填写');
      wx.hideLoading()
      this.setData({
        submit_disable:false
      })
    }
    this.refresh()
  },
  recieve_onClose() {
    this.setData({
      recieve_isShow: false
    })
  },
  //追问界面
  pump() {
    this.setData({
      pump_isShow: true
    })
  },
  send_pump() {
    this.setData({
      submit_disable:true
    })

    wx.showLoading({
      title: '加载中',
    })
    
    //暂停两秒
    var start=Date.now();
    while(true){
    var nowTime=Date.now();
    var offset=nowTime-start;
    if(offset>=2000)
    break;
    }

    if (this.data.pump_describe != '') {
      //提交问题
      // 获取页面数据????
    let date = new Date();  //当前标准时间格式
    var datenum = this.dtConvert(date).DateTime
    console.log(datenum)

    // 上传图片
    wx.cloud.init();
    const {
      fileList
    } = this.data;
    if (!fileList.length) {//无图片
      let that = this
      let that_id = this.data.Main.picker
      dbF.add({
        data:{
          date:datenum,
          des:this.data.pump_describe,
          img:this.data.img,
          mainid:this.data.id
        },
        success:function(res){
          wx.showToast({
            title: '提交成功!୧(๑•̀⌄•́๑)૭',
            icon: 'success',
            duration: 2000//持续的时间
          })

          //给义工发消息
          that.send_message(that_id)
          //给义工发弹窗
          that.send_message_to_vol(that_id)
          that.refresh()
        }
      })
      this.setData({
        pump_isShow:false,
        pump_describe:'',
        img:[],
        fileList: [],
      })

      this.setData({
        submit_disable:false
      })
    } else {//有图片
      const uploadTasks = fileList.map((file, index) => this.uploadFilePromise(`photo/${this.data.openid}-photo${index}${datenum}.png`, file));
      wx.showToast({
        title: '上传中',
        icon: 'loading'
      })
      Promise.all(uploadTasks)
        .then(res => {
          wx.showToast({
            title: '上传成功',
            icon: 'none'
          })

          var start=Date.now();
          while(true){
          var nowTime=Date.now();
          var offset=nowTime-start;
          if(offset>=2000)
          break;}
          
          this.setData({
            cloudPath: res,
            fileList: []
          })
          let that = this
          let that_id = this.data.Main.picker
          dbF.add({
            data:{
              date:datenum,
              des:this.data.pump_describe,
              img:this.data.img,
              mainid:this.data.id
            },
            success:function(res){
              wx.showToast({
                title: '提交成功!',
                icon: 'success',
                duration: 2000//持续的时间
              })
              
              //给义工发消息
              that.send_message(that_id)
              //给义工发弹窗
              that.send_message_to_vol(that_id)

              that.refresh()
            }
            
          })
          this.setData({
            pump_isShow:false,
            pump_describe:'',
            img:[],
            fileList: [],
          })

          this.setData({
            submit_disable:false
          })
        })
        .catch(e => {
          wx.showToast({
            title: '上传失败',
            icon: 'none'
          });
          console.log(e);
        });
    }
    //上传图片结束
    } else {
      Toast.fail('还有信息未填写');
      wx.hideLoading()
      this.setData({
        submit_disable:false
      })
    }
    this.refresh()
  },
  pump_onClose() {
    this.setData({
      pump_isShow: false
    })
  },
  done() {
    this.setData({
      //结束问答，状态改变
      scoreShow: true,
    })
    db.collection('Main').where({
      _id:this.data.id
    }).update({
      data:{
        state:'solved'
      }
      
    })
    Toast.success('请评分!୧(๑•̀⌄•́๑)૭');
    this.refresh()
  },
  //获取打分的值
  score_onChange(e) {
    this.setData({
      score: e.detail,
    })
  },
  score_onClose() {
    this.setData({
      scoreShow: false,
    })
    db.collection('Main').where({
      _id:this.data.id
    }).update({
      data:{
        score:this.data.score
      }
      
    })
    Toast.success('问答结束!୧(๑•̀⌄•́๑)૭');
    this.refresh()
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.refresh()
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    Toast.success('刷新成功!');
    this.refresh()
    wx.stopPullDownRefresh()
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})